import 'package:dio/dio.dart';
import 'package:dio_flutter_transformer/dio_flutter_transformer.dart';
import 'package:flutter_benchu/utils/commonPkg.dart';

// 支持的请求类型
enum Methods { POST, GET, DELETE, PUT, PATCH }

class Agent {
  Dio dio;
  Agent() {
    final BaseOptions baseOptions = BaseOptions(
      baseUrl: '',
      connectTimeout: 8000, //建立tcp做大延时
      receiveTimeout: 15000, //请求超时时间
      headers: <String, String>{
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/json',
      },
    );
    dio = Dio(baseOptions);
    dio.transformer = FlutterTransformer();
    dio.interceptors.add(InterceptorsWrapper(onRequest: requestBefore, onResponse:requestAfter, onError: (DioError e) => e));
  }
  
  // 请求拦截器
  requestBefore(RequestOptions options) async{
    // 添加 token  ...等
    return options;
  }

  // 响应拦截器
  requestAfter(Response response) async {
    return response;
  }

  Future<Map> request(
    {
      Methods method,                               //请求方式
      String baseUrl,                               //网址  
      String url,                                   //接口地址
      Map<String, dynamic> params,                  //url参数
      Map<String, dynamic> header,                  //header
      Map<String, dynamic> data,                    //body参数
      doEncrypt = false,                            //是否开启加密
    }
  ) async {
      params = params??{};
      header = header??{};
      data = data??{};
      Response res;
      var allUrl = baseUrl + url;
      var options =        Options(headers:header);
      var encryptOptions = Options(headers: header, extra: {'doEncrypt': doEncrypt});
      if(method == Methods.POST)     res = await dio.post(allUrl,data: data,options:encryptOptions);
      if(method == Methods.GET)      res = await dio.get(allUrl,queryParameters: params,options:encryptOptions);
      if(method == Methods.PUT)      res = await dio.put(allUrl,data: data,options: options);
      if(method == Methods.DELETE)   res = await dio.delete(allUrl,data: data,options: options);
      if(method == Methods.PATCH)    res = await dio.patch(allUrl,data: data,options: options);

      // 处理结果
      int statusCode=res.statusCode;
      // 浏览器 200 系列code处理
      if (statusCode >= 200 && statusCode < 300) {
        if (res.data == null || res.data == '')   return _handError('data is null url:' + allUrl, 888001);  //接口数据异常 数据为空
        if (res.data['code'] == null)             return _handError('code is null url:' + allUrl, 888002);  //接口数据异常 code为空
        return res.data;
      }
      if (statusCode >= 300 && statusCode < 400)  return _handError('连接服务器超时', 503);   //浏览器 3 系列code处理      http请求异常
      if (statusCode >= 400 || statusCode >= 500) return _handError('连接服务器超时', 503);   //浏览器 4,5,6 系列code处理  http请求异常
  }

  // 处理错误
  Map _handError(String errorMsg, int code) {
    _printLog('error code : $code  *************');
    _printLog(errorMsg);
    return {'code': code, 'data': null, 'msg': errorMsg};
  }

  // 打印
  _printLog(Object object) {
    Log.v(object, tag: netTag);
  }

  // 切换请求地址
  changeHostUrl(String hostUrl) {
    dio.options.baseUrl = hostUrl;
  }
}


final agent = Agent();